package com.cyou.nad.datastore.query.dialect;

import com.cyou.nad.dao.Pagination;

public class Oracle9iDialect implements Dialect {

	public String getLimitString(String sql, boolean hasOffset) {

		sql = sql.trim();
		boolean isForUpdate = false;
		if (sql.toLowerCase().endsWith(" for update")) {
			sql = sql.substring(0, sql.length() - 11);
			isForUpdate = true;
		}

		StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);
		if (hasOffset) {
			pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
		} else {
			pagingSelect.append("select * from ( ");
		}
		pagingSelect.append(sql);
		if (hasOffset) {
			pagingSelect.append(" ) row_ ) where  rownum_ > ?  and rownum_ <= ? ");
		} else {
			pagingSelect.append(" ) where rownum <= ?");
		}

		if (isForUpdate) {
			pagingSelect.append(" for update");
		}

		return pagingSelect.toString();
	}

	@Override
	public Object[] getLimitParam(int pageNo,int pageSize, boolean hasOffset) {
		if(hasOffset) {
			int start = getStartOfPage(pageNo,pageSize);
			return new Object[]{start,start+pageSize};
		}
		return new Object[]{pageSize};
	}

	int getStartOfPage(int pageNo, int pageSize) {
		return (pageNo - 1) * pageSize;
	}



}
